package com.weme.common.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat

class CirclePagerIndicator @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) {


    private val circlePaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val circleRadius = 8f  // 圆的半径
    private val circleSpacing = 24f  // 圆之间的间距
    private var pageCount = 0
    private var currentPage = 0

    init {
        val color = ContextCompat.getColor(context, com.weme.common.R.color.white)  // 替换成你的圆的颜色
        circlePaint.color = color
    }


    fun setCurrentPage(currentPage: Int) {
        this.currentPage = currentPage
        invalidate() // 刷新视图以重新绘制指示器
    }


    fun setPageCount(pageCount: Int) {
        this.pageCount = pageCount
        invalidate() // 刷新视图以重新绘制指示器
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val width = paddingLeft + paddingRight + (pageCount - 1) * circleSpacing + 2 * circleRadius
        val height = paddingTop + paddingBottom + 2 * circleRadius
        setMeasuredDimension(resolveSizeAndState(width.toInt(), widthMeasureSpec, 0), resolveSizeAndState(height.toInt(), heightMeasureSpec, 0))
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val totalWidth = width.toFloat()
        val totalHeight = height.toFloat()
        val startX = (totalWidth - pageCount * (2 * circleRadius + circleSpacing)) / 2

        for (i in 0 until pageCount) {
            val cx = startX + i * (2 * circleRadius + circleSpacing) + circleRadius
            val cy = totalHeight / 2
            val radius = circleRadius

            val circleColor = if (i == currentPage) { // 当前页的颜色
                ContextCompat.getColor(context, com.example.resources.R.color.selected_circle_color)
            } else { // 非当前页的颜色
                ContextCompat.getColor(context, com.example.resources.R.color.unselected_circle_color)
            }

            circlePaint.color = circleColor
            canvas.drawCircle(cx, cy, radius, circlePaint)
        }

    }
}
